<template>
  <div style="margin: 0em 0.35em ">
  <template v-for="item in articleList" :key="item.id">
    <el-card :body-style="{ padding: '0px' }"  @click="articleDetail(item)">
      <div style="padding: 14px">
        <span style="font-size: 14px;"> 作者：{{ userNames[item.userinfoId]?userNames[item.userinfoId]:"暂无用户" }}
          分类：{{allCatsList.find(obj=>item.articleCatId==obj.id)?.catName?allCatsList.find(obj=>item.articleCatId==obj.id)?.catName:'暂无板块'}}</span>
        <div>
          <span text class="button"> {{  ellipsis(item.title) }}</span>
        </div>
        <time class="time"> {{ dateConversion(item.updateTime) }}</time>
      </div>
    </el-card>
  </template>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getArticlesAll,getArticlesByCateId } from '@/http/article.js'
import { getUserNameById } from '@/http/user.js'
import { ElMessage } from 'element-plus'
import {useRouter} from "vue-router";
import {useUserToken} from "@/store/counter";
const userToken=useUserToken();
const articleList = ref([])
const allCatsList = ref([]) //articleCatId
const userNames = reactive({})  // reactive 响应式对象
const router=useRouter()
onMounted(async () => {
  await getArticles();
})
function dateConversion(dateOld){
  const date = new Date(dateOld);
  const formattedDate = `${date.getFullYear()}-${('0' + (date.getMonth()+1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`;
  return formattedDate;
}
function ellipsis(value){
  if (value.length > 45) {
    return value.slice(0,45) + '...'
  }
  return value
}

async function updateDate(cateId) {
  if (cateId) {
    try {
      const res = await getArticlesByCateId(cateId);
      if (res.success) {
        const articles = res.data.articles;
        userNameData(articles);
        articleList.value = articles;
        ElMessage({
          type: 'success',
          message: res.msg,
        });
      } else {
        ElMessage.error(res.msg);
      }
    } catch (err) {
      ElMessage.error(err.message);
    }
  } else {
    getArticles();
  }
}

function getArticles() {
  getArticlesAll().then(res => {
    if (res.success) {
      const articles = res.data.articles;
      userNameData(articles);
      articleList.value = articles;
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    ElMessage.error(err.message);
  });
}

async function userNameData(articles) {
  for (const valueElement of articles) {
    await articlesUser(valueElement.userinfoId);
  }
}
const articlesUser = userId => {
  getUserNameById(userId).then(res => {
    userNames[userId] = res.data?.userinfo?.userName?res.data?.userinfo?.userName:userId;  // 直接修改响应式对象的属性
  })
}
const articleDetail = (item) => {
  userToken.setUserInfo(item)
  router.push({
    name:'articles',
  })
};

defineExpose({
  updateDate
})
</script>

<style scoped>
.time {
  font-size: 12px;
  color: #999;
  float: right;
}

.button {
  padding: 0;
  min-height: auto;
}

</style>
